import { StyleSheet, Text, View, Image, Pressable, Modal, StatusBar, Vibration, Animated } from 'react-native';
import React, { useRef, useEffect, useState } from 'react';
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import Sound from 'react-native-sound';
import { useTranslation } from 'react-i18next';
import { observer, webSocketStore } from '~/store';
import { answerCall } from '~/api/deviceApi';
import { exitChannel } from '~/utils/socketMessenger';
import { navigate } from '~/router/navigation';
import { useCirculationAnimation } from '~/common';
import { isIos, px2dp, scale, statusBarHeight, width } from '~/utils/px2dp';
import { handlePermissions, checkPermissions } from '~/utils/permission';

export default observer(() => {
    const { t } = useTranslation();
    const modalizeRef = useRef<any>(null);
    const timeoutRef = useRef<NodeJS.Timeout | null>(null);
    const isAnsweringRef = useRef(false);

    const [localVisible, setLocalVisible] = useState(false); // 本地控制 Modal 显示

    const { inComingVisible, inComingCall } = webSocketStore;

    const animation = useCirculationAnimation({ duration: 3000, start: true });
    const scale = animation.interpolate({
        inputRange: [0, 0.1, 0.2, 0.3, 0.4, 1],
        outputRange: [1, 1.09, 1.03, 1.09, 1, 1],
    });

    Sound.setCategory('Playback');

    // 同步来电显示状态，只触发一次弹窗
    useEffect(() => {
        if (inComingVisible && !webSocketStore.isHandlingCall) {
            setLocalVisible(true);
        }
    }, [inComingVisible]);

    // Modal 弹出后的副作用处理
    useEffect(() => {
        if (!localVisible) return;

        checkPermissions();
        let whoosh;

        modalizeRef.current?.fadeInUp(1000);
        Vibration.vibrate([0, 500, 1000], true);
        whoosh = new Sound('call_sound.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
                console.log('加载音频失败', error);
                return;
            }
            whoosh.setVolume(1);
            whoosh.setNumberOfLoops(-1);
            whoosh.play();
        });

        timeoutRef.current = setTimeout(() => {
            webSocketStore.hideInComingModal();
            setLocalVisible(false);
        }, 70000);

        return () => {
            if (whoosh) {
                whoosh.stop(() => {
                    whoosh.release();
                });
            }
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
            }
            Vibration.cancel();
        };
    }, [localVisible]);

    // 拒绝来电
    const hangup = async () => {
        await answerResult(2);
        webSocketStore.isHandlingCall = true;
        setLocalVisible(false);
        webSocketStore.hideInComingModal();
        exitChannel(inComingCall.user.device_sn);
    };

    // 接听电话
    const answer = async () => {
        webSocketStore.hideInComingModal(); // 👈 尝试关闭 Modal
        const hasPermission = await handlePermissions('both');
        if (isAnsweringRef.current) return;
        isAnsweringRef.current = true;
        webSocketStore.isHandlingCall = true;
        setLocalVisible(false);
        const callInfo = {
            device_sn: inComingCall.user.device_sn,
            user_name: inComingCall.user.name,
            to_uid: inComingCall.user.user_id,
            to_token: inComingCall.agora.token,
            fo_uid: inComingCall.agora.user_id,
            channel_id: inComingCall.agora.channel_id,
            type: 'inComing',
        };
        if (isIos()) {
            answerResult(1);
            navigate('CallDevice', callInfo);
        } else {
            if (hasPermission) {
                answerResult(1);
                navigate('CallDevice', callInfo);
            } else {
                console.log('权限被拒绝');
            }
        }
        isAnsweringRef.current = false;
    };

    const answerResult = (type) => {
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
            timeoutRef.current = null;
        }
        answerCall({
            call_id: inComingCall.call_id,
            type: type,
        });
    };

    return (
        <Modal
            animationType={'none'}
            visible={localVisible}
            statusBarTranslucent={true}
            animated={true}
            transparent={false}
            hardwareAccelerated={true}>
            <View style={styles.modal}>
                <StatusBar hidden={true} />
                <LinearGradient colors={['#385149', '#595E53', '#38514A']} style={styles.container}>
                    <Animatable.View style={styles.content} ref={modalizeRef}>
                        <View style={styles.header}>
                            <Image
                                style={styles.avatar}
                                source={{
                                    uri:
                                        inComingCall.user?.avatar_url ||
                                        'https://bjy.oss-cn-shenzhen.aliyuncs.com/pic/20231202/2911701480341.png',
                                }}
                            />
                            <Text style={styles.user_name}>{inComingCall.user?.name || '用户'}</Text>
                        </View>
                        <View style={[styles.row, styles.menue]}>
                            <Pressable style={styles.listIcons} onPress={hangup}>
                                <Image source={require('~/assets/call/hangup.png')} style={styles.icons} />
                                <Text style={styles.t1}>{t('CallNoticeModal.t1')}</Text>
                            </Pressable>
                            <Animated.View style={[styles.listIcons, { transform: [{ scale }] }]}>
                                <Pressable onPress={answer} style={styles.listIcons}>
                                    <Image source={require('~/assets/call/answer.png')} style={styles.icons} />
                                    <Text style={styles.t1}>{t('CallNoticeModal.t2')}</Text>
                                </Pressable>
                            </Animated.View>
                        </View>
                    </Animatable.View>
                </LinearGradient>
            </View>
        </Modal>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    modal: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    container: {
        flex: 1,
    },
    content: {
        width: width,
        flex: 1,
        paddingTop: statusBarHeight,
    },
    header: {
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: '20%',
    },
    avatar: {
        width: px2dp(140),
        height: px2dp(140),
        borderRadius: px2dp(70),
    },
    user_name: {
        color: '#fff',
        fontSize: scale(40),
        fontWeight: 'bold',
        marginTop: px2dp(12),
    },
    icons: {
        width: px2dp(120),
        height: px2dp(120),
    },
    listIcons: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    t1: {
        marginTop: px2dp(14),
        color: '#fff',
        fontSize: scale(30),
    },
    menue: {
        justifyContent: 'space-around',
        position: 'absolute',
        width: '100%',
        bottom: '10%',
    },
    postionCopy: {
        position: 'absolute',
        top: px2dp(20),
        right: px2dp(32),
        zIndex: 100,
    },
});
